package cn.lysj.framework.base;

import cn.lysj.framework.common.exception.MyException;
import cn.lysj.framework.common.utils.web.ParamUtil;
import cn.lysj.framework.common.utils.web.Resp;
import cn.lysj.framework.common.validate.exception.ValidatorException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class BaseContent {


    @ExceptionHandler(Exception.class)
    public Resp handleException(Exception e) {
        e.printStackTrace();
        StackTraceElement[] stackTraceElements = e.getStackTrace();
        log.error(stackTraceElements[0]+"--"+e.toString());
        if (e instanceof MyException) {
            MyException myException = (MyException) e;
            Resp resp = new Resp(myException.getMessage());
            resp.setCode(ParamUtil.isBlank(myException.getCode()) ? Resp.INNER_ERROR : myException.getCode());
            return resp;
        }
        return new Resp(Resp.INNER_ERROR, "oops!");
    }

    @ExceptionHandler(ValidatorException.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Resp processValidatorException(ValidatorException ex) {
        return new Resp(Resp.PARAM_ERROR,ex.getMessage());
    }

    @Resource
    protected HttpServletRequest request;
    @Resource
    protected HttpServletResponse response;


}
